package ProxyMod;

import java.util.HashMap;

public class code {
    // 抽象主题类

    abstract class Subject {

        public abstract String getContent(String key);

        public abstract void add(String key, String value);
    }

// 真实主题类
    class Memory extends Subject {

        private HashMap<String, String> pool = new HashMap<>();

        @Override
        public String getContent(String key) {
            return pool.get(key);
        }

        @Override
        public void add(String key, String value) {
            pool.put(key, value);
        }
    }

// 代理类
    class CacheProxy extends Subject {

        private HashMap<String, String> cache = new HashMap<>();
        private Memory memory;

        public CacheProxy(Memory memory) {
            this.memory = memory;
        }

        @Override
        public String getContent(String key) {
            // 先检查缓存中是否存在数据
            if (cache.containsKey(key)) {
                System.out.println("Returning data from cache for key: " + key);
                return cache.get(key);
            } else {
                // 缓存中不存在，从内存中获取并存储到缓存
                String value = memory.getContent(key);
                if (value != null) {
                    cache.put(key, value);
                    System.out.println("Data retrieved from memory and stored in cache for key: " + key);
                }
                return value;
            }
        }

        @Override
        public void add(String key, String value) {
            // 添加数据到内存和缓存
            memory.add(key, value);
            cache.put(key, value);
        }
    }

}
